package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.context.BaseContext;
import com.sky.dto.SetmealDTO;
import com.sky.dto.SetmealPageQueryDTO;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.exception.BaseException;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.SetmealService;
import com.sky.vo.SetmealVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * TODO
 *
 * @Author mr.Candy
 * @Date 2025/6/415:43
 */
@Service
@Slf4j
public class SetmealServiceImpl implements SetmealService{
    @Autowired
    private SetmealMapper setmealMapper;

    /**
     * 套餐分页查询
     *
     * @param dto
     * @return
     */
    @Override
    public PageResult page(SetmealPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        Page<SetmealVO> page = setmealMapper.page(dto);
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 新增套餐,同事需要保存套餐和菜品的关联关系
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveWithDish(SetmealDTO dto) {
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(dto,setmeal);//这里创建人创建时间更新人更新时间没处理
        setmeal.setCreateTime(LocalDateTime.now());
        setmeal.setUpdateTime(LocalDateTime.now());
        setmeal.setCreateUser(BaseContext.getCurrentId());
        setmeal.setUpdateUser(BaseContext.getCurrentId());
        //插入套餐数据
        setmealMapper.insertSetmeal(setmeal);
        if (setmeal.getId() == null) {
            throw new BaseException("插入套餐失败，未获取到主键");
        }
        //处理关系表的数据
        List<SetmealDish> setmealDishes = dto.getSetmealDishes();
        setmealDishes.forEach(dish -> {
            dish.setSetmealId(setmeal.getId());
        });
        //插入套餐和菜品的关联关系数据
        setmealMapper.insertBatch(setmealDishes);
    }
}
